package com.ycu.jk16.mall.controller.admin;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.ycu.jk16.mall.domain.*;
import com.ycu.jk16.mall.service.CategoryService;
import com.ycu.jk16.mall.service.ProductService;
import com.ycu.jk16.mall.util.common.AndroidMalConstant;
import com.ycu.jk16.mall.util.common.ResponseJsonUtils;

@Controller
@RequestMapping(value = "/manage/product")
public class AdminProductController {
	@Autowired
	@Qualifier("productService")
	private ProductService productService;

	@Autowired
	@Qualifier("categoryService")
	private CategoryService categoryService;

	@RequestMapping(value = "/list")
	public void list_do(@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		List<Object> list = new ArrayList<Object>();
		Map<String, Object> tempInfo;
		List<Product> products;

		try {
			params.put("pageNum", pageNum);
			params.put("pageSize", pageSize);
			products = productService.productList(params);
			int totalPages = productService.countProduct() / pageSize + productService.countProduct() % pageSize == 0
					? 0 : 1;
			for (int i = 0; i < products.size(); i++) {
				tempInfo = new HashMap<String, Object>();
				tempInfo.put("id", products.get(i).getId());
				tempInfo.put("categoryId", products.get(i).getCategory().getId());
				tempInfo.put("name", products.get(i).getName());
				tempInfo.put("subtitle", products.get(i).getSubtitle());
				tempInfo.put("mainImage", products.get(i).getMainImage());
				tempInfo.put("status", products.get(i).getStatus());
				tempInfo.put("price", products.get(i).getPrice());
				list.add(tempInfo);
			}

			tempInfo = new HashMap<String, Object>();
			tempInfo.put("pageNum", pageNum);
			tempInfo.put("pageSize", pageSize);
			tempInfo.put("size", products.size());
			tempInfo.put("orderBy", null);
			tempInfo.put("total", productService.countProduct());
			tempInfo.put("pages", totalPages);
			tempInfo.put("list", list);
			tempInfo.put("firstPage", 1);
			tempInfo.put("prePage", pageNum > 1 ? pageNum - 1 : pageNum);
			tempInfo.put("nextPage", pageNum < totalPages ? pageNum + 1 : pageNum);
			tempInfo.put("lastPage", totalPages);
			tempInfo.put("isFisrtPage", pageNum == 1 ? "true" : "false");
			tempInfo.put("isLastPage", pageNum == totalPages ? "true" : "false");
			tempInfo.put("hasPreviousPage", pageNum > 1 ? "true" : "false");
			tempInfo.put("hasNextPage", pageNum < totalPages ? "true" : "false");

			// 加入json数据
			data.put("status", 0);
			data.put("data", tempInfo);
		} catch (Exception e) {
			data.put("status", 10);
			data.put("msg", "用户未登录,请登录");
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/search")
	public void search_do(String productName, Integer productId,
			@RequestParam(value = "pageNum", defaultValue = "1") int pageNum,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize, HttpServletResponse response) {
		Map<String, Object> params = new HashMap<String, Object>();
		Map<String, Object> data = new HashMap<String, Object>();
		List<Object> list = new ArrayList<Object>();
		Map<String, Object> tempInfo;
		List<Product> products;

		try {
			params.put("productName", productName);
			params.put("productId", productId);
			params.put("pageNum", pageNum);
			params.put("pageSize", pageSize);
			products = productService.productList(params);
			int totalPages = productService.countProduct() / pageSize + productService.countProduct() % pageSize == 0
					? 0 : 1;
			for (int i = 0; i < products.size(); i++) {
				tempInfo = new HashMap<String, Object>();
				tempInfo.put("id", products.get(i).getId());
				tempInfo.put("categoryId", products.get(i).getCategory().getId());
				tempInfo.put("name", products.get(i).getName());
				tempInfo.put("subtitle", products.get(i).getSubtitle());
				tempInfo.put("mainImage", products.get(i).getMainImage());
				tempInfo.put("status", products.get(i).getStatus());
				tempInfo.put("price", products.get(i).getPrice());
				list.add(tempInfo);
			}

			tempInfo = new HashMap<String, Object>();
			tempInfo.put("pageNum", pageNum);
			tempInfo.put("pageSize", pageSize);
			tempInfo.put("size", products.size());
			tempInfo.put("orderBy", null);
			tempInfo.put("total", productService.countProduct());
			tempInfo.put("pages", totalPages);
			tempInfo.put("list", list);
			tempInfo.put("firstPage", 1);
			tempInfo.put("prePage", pageNum > 1 ? pageNum - 1 : pageNum);
			tempInfo.put("nextPage", pageNum < totalPages ? pageNum + 1 : pageNum);
			tempInfo.put("lastPage", totalPages);
			tempInfo.put("isFisrtPage", pageNum == 1 ? "true" : "false");
			tempInfo.put("isLastPage", pageNum == totalPages ? "true" : "false");
			tempInfo.put("hasPreviousPage", pageNum > 1 ? "true" : "false");
			tempInfo.put("hasNextPage", pageNum < totalPages ? "true" : "false");

			// 加入json数据
			data.put("status", 0);
			data.put("data", tempInfo);
		} catch (Exception e) {
			data.put("status", 10);
			data.put("msg", "用户未登录,请登录");
			e.printStackTrace();
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/detail")
	public void search_do(Integer productId, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> pinfo = new HashMap<String, Object>();

		Product product;

		try {
			product = productService.selectById(productId);

			pinfo.put("id", product.getId());
			pinfo.put("categoryId", product.getCategory().getId());
			pinfo.put("parentCategoryId", product.getCategory().getParentCategory().getId());
			pinfo.put("name", product.getName());
			pinfo.put("subtitle", product.getSubtitle());
			pinfo.put("imageHost", product.getImageHost());
			pinfo.put("mainImage", product.getMainImage());
			List<ProductPhoto> photos = productService.selectProductPhotoListById(productId);
			String subImage = "[";
			if (photos.size() > 0) {
				subImage += "\"" + photos.get(0).getSubImage() + "\"";
			}
			for (int i = 1; i < photos.size(); i++) {
				subImage += ",\"" + photos.get(i).getSubImage() + "\"";
			}
			subImage += "]";
			pinfo.put("subImages", subImage);
			pinfo.put("detail", product.getDetail());
			pinfo.put("price", product.getPrice());
			pinfo.put("stock", product.getStock());
			pinfo.put("status", product.getStatus());
			pinfo.put("createTime", product.getCreateTime());
			pinfo.put("updateTime", product.getUpdateTime());

			// 加入json数据
			data.put("status", 0);
			data.put("data", pinfo);
		} catch (Exception e) {
			data.put("status", 1);
			data.put("msg", "没有权限");
			e.printStackTrace();
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/save")
	public void save_do(@RequestParam("categoryId") Integer categoryId, @RequestParam("name") String name,
			@RequestParam("subtitle") String subtitle, @RequestParam("mainImage") CommonsMultipartFile mainImage,
			@RequestParam("subImages") CommonsMultipartFile[] subImages, @RequestParam("detail") String detail,
			@RequestParam("price") java.math.BigDecimal price, @RequestParam("stock") Integer stock,
			@RequestParam("status") Integer status, @RequestParam(value = "id", defaultValue = "-1") Integer id,
			HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		Product product = new Product();

		try {

			product.setName(name);
			product.setSubtitle(subtitle);
			product.setDetail(detail);
			product.setPrice(price);
			product.setStock(stock);
			product.setStatus(status);
			product.setUpdateTime(new java.sql.Date(new Date().getTime()));

			if (id < 0) {
				Category catg = categoryService.findCategoryById(categoryId);
				product.setCategory(catg);
				product.setParentCategory(catg.getParentCategory());
				product.setCreateTime(new java.sql.Date(new Date().getTime()));
				product.setImageHost(AndroidMalConstant.HOST_ADDRESS);

				product.setMainImage(savefile(mainImage));

				productService.saveProduct(product);

				int lid = productService.lastProductId(name);

				for (int i = 0; i < subImages.length; i++) {
					ProductPhoto paramProductPhoto = new ProductPhoto();
					paramProductPhoto.setId(lid);
					paramProductPhoto.setSubImage(savefile(subImages[i]));
					productService.saveProductPhoto(paramProductPhoto);
				}

				data.put("status", 0);
				data.put("data", "新增产品成功");

			} else {

				product.setId(id);

				if (categoryId != null && !categoryId.equals("")) {
					Category catg = categoryService.findCategoryById(categoryId);
					product.setCategory(catg);
					product.setParentCategory(catg.getParentCategory());
				}

				if (!mainImage.isEmpty()) {
					product.setMainImage(savefile(mainImage));
					Product op = productService.selectById(id);
					delFile(op.getMainImage());
				}

				productService.updateProduct(product);

				if (subImages.length > 0) {

					List<ProductPhoto> photos = productService.selectProductPhotoListById(id);

					for (int i = 0; i < photos.size(); i++) {
						delFile(photos.get(i).getSubImage());
					}
					productService.deleteProductPhotoById(id);

					for (int i = 0; i < subImages.length; i++) {
						ProductPhoto paramProductPhoto = new ProductPhoto();
						paramProductPhoto.setId(id);
						paramProductPhoto.setSubImage(savefile(subImages[i]));
						productService.saveProductPhoto(paramProductPhoto);
					}
				}

				data.put("status", 0);
				data.put("data", "更新产品成功");
			}

		} catch (Exception e) {

			data.put("status", 1);
			data.put("data", "更新产品失败");
			e.printStackTrace();

		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/set_sale_status")
	public void set_sale_status(Integer status, Integer productId, HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		Product product = new Product();

		try {
			product.setStatus(status);
			product.setUpdateTime(new java.sql.Date(new Date().getTime()));

			product.setId(productId);

			productService.updateProduct(product);

			data.put("status", 0);
			data.put("data", "修改产品状态成功");

		} catch (Exception e) {

			data.put("status", 1);
			data.put("data", "修改产品状态失败");
			e.printStackTrace();

		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/upload")
	public void uploadImage(@RequestParam("upload_file") CommonsMultipartFile upload_file,
			HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();
		Map<String, Object> urlData = new HashMap<String, Object>();

		try {
			String name = savefile(upload_file);

			urlData.put("uri", name);
			urlData.put("url", AndroidMalConstant.HOST_ADDRESS + "/" + name);

			data.put("status", 0);
			data.put("data", urlData);
		} catch (Exception e) {
			data.put("status", 1);
			data.put("msg", "上传失败");
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	@RequestMapping(value = "/richtext_img_upload")
	public void richtext_img_upload(@RequestParam("upload_file") CommonsMultipartFile upload_file,
			HttpServletResponse response) {
		Map<String, Object> data = new HashMap<String, Object>();

		try {
			String name = savefile(upload_file);

			data.put("msg", "上传成功");
			data.put("file_path", AndroidMalConstant.HOST_ADDRESS + "/" + name);
			data.put("success", true);
		} catch (Exception e) {
			data.put("msg", e.getMessage());
			data.put("file_path", "");
			data.put("success", false);
		} finally {
			ResponseJsonUtils.json(response, data);
		}
	}

	String savefile(CommonsMultipartFile file) throws IllegalStateException, IOException {
		String path = new Date().getTime() + file.getOriginalFilename();
		String dir = getClass().getResource("/").getPath();
		dir = dir.substring(0, dir.indexOf("WEB-INF"));
		File newFile = new File(dir + "Images/" + path);
		if (!newFile.exists()) {
			newFile.mkdirs();
		}
		file.transferTo(newFile);
		return path;
	}

	void delFile(String filename) {
		String dir = getClass().getResource("/").getPath();
		dir = dir.substring(0, dir.indexOf("WEB-INF"));
		File file = new File(dir + "Images/" + filename);
		if ((file.exists()) && (file.isFile())) {
			file.delete();
		}
	}

}
